package com.xuliugen.jwt.demo.conf;

import com.xuliugen.jwt.demo.filter.JWTAuthFilter;
import com.xuliugen.jwt.demo.filter.JWTLoginFilter;
import com.xuliugen.jwt.demo.service.security.CustomAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * SpringSecurity的配置
 * 通过SpringSecurity的配置，将JWTLoginFilter，JWTAuthenticationFilter组合在一起
 * @author xuliugen
 * @date 2018/2/1
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 设置 HTTP 验证规则
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                //所有不需要登录之后才可以操作的请求，例如：/user/register等请求，都放行
                .antMatchers(HttpMethod.POST, "/user/register").permitAll()
                //所有请求需要身份认证
                .anyRequest().authenticated()
                .and()
                //添加用户登录过滤器
                .addFilter(new JWTLoginFilter(authenticationManager()))
                //添加用户认证过滤器
                .addFilter(new JWTAuthFilter(authenticationManager()));
    }

    /**
     * 使用自定义身份验证组件
     * @param auth
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(new CustomAuthenticationProvider(userDetailsService, bCryptPasswordEncoder));
    }

}
